﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Generic; 
using System.Web.UI; 
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using System.IO; 
using KPIS.Utils;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_TimeAttendants : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private ITimeAttendantsBLL TimeAtt = new TimeAttendantsBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private IJobSiteBLL jobsiteBLL = new JobSiteBLL();
        private IEmployeeTypeBLL emptypeBLL = new EmployeeTypeBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                FillDataToEmpType();
                FillDataToJobSite();
                cmbWorkingJobSite.SelectedValue = GetWorkingJobSite();                
                LoadDataGrid();
            }
        }
        protected string GetWorkingJobSite()
        {
            string WorkingJobSite = "";

            DataSet ds = empBLL.LoadEmployees(ssMng.EmpSeqI, "", true, "");
            DataTable dt = null;
            if (ds != null)
            {
                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    WorkingJobSite = dt.Rows[0]["WORKING_JOB_SITE_SEQ"].ToString();
            }

            return WorkingJobSite;
        }
        public void FillDataToEmpType()
        {
            IList<EmployeeTypeInfo> InfoList = emptypeBLL.ListEmployeeTypes(null);

            cmbEmpType.DataSource = InfoList;
            cmbEmpType.DataBind();
        }
        protected void FillDataToJobSite()
        {
            JobSiteTypeInfo Info = new JobSiteTypeInfo();
            DataSet ds = jobsiteBLL.LoadJobSites("", SystemInfo._JobsiteInternal, "", "");
            DataTable dt = new DataTable();
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }

            cmbWorkingJobSite.DataSource = dt;
            cmbWorkingJobSite.DataBind();
        }
        public void LoadDataGrid()
        {
            string EmployeeType = cmbEmpType.SelectedValue;
            string WorkingDate = string.IsNullOrEmpty(txtDateWorking.Text) ? "" : txtDateWorking.TextWithLiterals;
            DataSet ds = TimeAtt.LoadTimeAttendants(EmployeeType, WorkingDate, cmbWorkingJobSite.SelectedValue, "");
            DataTable dt = null;

            if (ds != null)
                dt = ds.Tables[0];

            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }
        protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["working_seq"]);
                TimeAtt.Delete(seq, ssMng.EmpSeqI);
            }

            if (e.CommandName == "ExpandCollapse")
                return;

            Session["EMPTYPE"] = cmbEmpType.SelectedValue;
            Session["WORKING"] = cmbWorkingJobSite.SelectedValue;
            LoadDataGrid();
        }

        protected void btnLoad_Click(object sender, EventArgs e)
        {
            StreamReader strWer;
            try
            {
                if (attachment.PostedFile != null)
                {
                    string fileName = attachment.PostedFile.FileName;
                    string pathName = Server.MapPath("../timeAttFile/");                     
                    if (!Directory.Exists(pathName)) Directory.CreateDirectory(pathName);
                    pathName += Path.GetFileName(fileName);
                    if (!File.Exists(pathName))
                    {
                        attachment.PostedFile.SaveAs(pathName);
                        strWer = File.OpenText(pathName);
                        DataTable dtScanTmp = new DataTable();
                        dtScanTmp.Columns.Add("code_scan", typeof(int));
                        dtScanTmp.Columns.Add("my_date", typeof(DateTime));
                        dtScanTmp.Columns.Add("my_time", typeof(TimeSpan));
                        dtScanTmp.Columns.Add("machine", typeof(string));
                        dtScanTmp.Columns.Add("my_endtime", typeof(TimeSpan));
                        ArrayList arrListStr = new ArrayList();
                        while (!(strWer.EndOfStream))
                        {
                            string strLine = strWer.ReadLine();
                            //strLine.Replace(" ", "");
                            string[] arrStr = strLine.Split(' ');
                            if (arrStr.Length != 7)
                            {
                                File.Delete(pathName);
                                return;
                            }

                            foreach (string strField in arrStr)
                            {
                                if (strField.Length > 0)
                                {
                                    arrListStr.Add(strField);
                                }
                            }

                            string y = arrListStr[1].ToString().Substring(0, 2);
                            if (int.Parse(y) < 50)
                                y = (Convert.ToInt32("20" + y) + 543).ToString();
                            else
                                y = "25"+y;
                            string m = arrListStr[1].ToString().Substring(2, 2);
                            string d = arrListStr[1].ToString().Substring(4, 2);
                            string myScan = arrListStr[0].ToString();
                            string myDate = y + "-" + m + "-" + d;
                            string myTime = Convert.ToInt32(arrListStr[2]) == 0 ? "00:00" : Convert.ToInt32(arrListStr[2]).ToString("##:##");
                            myTime = myTime.Length < 4 ? myTime = "00:00" : myTime;
                            string myEndTime = Convert.ToInt32(arrListStr[4]) == 0 ? "00:00" : Convert.ToInt32(arrListStr[4]).ToString("##:##");
                            myEndTime = myEndTime.Length < 4 ? myEndTime = "00:00" : myEndTime;
                            string myMach = arrListStr[3].ToString();
                            dtScanTmp.Rows.Add(myScan, myDate, myTime, myMach, myEndTime);

                            arrListStr.Clear();
                        }
                        dtScanTmp.AcceptChanges();
                        DataView dv = new DataView();
                        dv = dtScanTmp.DefaultView;
                        dv.Sort = "code_scan asc, my_time asc";
                        dtScanTmp = dv.ToTable();
                        strWer.Close();

                        foreach(DataRow row in dtScanTmp.Rows )
                        {
                            string CodeScan = row["code_scan"].ToString();
                            string EmpSeq = TimeAtt.GetEmpSequence(CodeScan);
                            string WorkingDate = row["my_date"].ToString();
                            string WorkingStart = row["my_time"].ToString() == "00:00:00" ? null : row["my_time"].ToString();
                            string WorkingEnd = row["my_endtime"].ToString() == "00:00:00" ? null : row["my_endtime"].ToString();
                            string WorkingStatus = row["machine"].ToString() == "" ? "" : row["machine"].ToString();

                            int EmpSequence = EmpSeq.Length > 0 ? Int32.Parse(EmpSeq) : 0;
                            //ใช้ตอน LoadTimeAttendants_NewMod 
                            string temp_wkdate = Convert.ToDateTime(WorkingDate).ToString("yyyy-MM-dd", new System.Globalization.CultureInfo("en-US"));

                            if (!TimeAtt.CheckDuplicate(EmpSeq, temp_wkdate))
                            {
                                TimeAtt.Insert(WorkingDate
                                    , EmpSequence
                                    , WorkingStart
                                    , WorkingEnd
                                    , ""
                                    , ""
                                    , ssMng.EmpSeqI);
                            }
                            else
                            {                               
                                int seq = 0;

                                IList<TimeAttendantInfo> lst = TimeAtt.LoadTimeAttendants_NewMod(temp_wkdate, EmpSeq);
                                foreach(TimeAttendantInfo t in lst){
                                    seq = t.working_seq;
                                }
                           
                                    if (seq == 0) break;
                                    TimeAtt.Update(seq
                                        , WorkingDate 
                                        , EmpSequence
                                        , WorkingStart
                                        , WorkingEnd
                                        , WorkingStatus
                                        , ""
                                        , ssMng.EmpSeqI);                                           
                            }
                        }

                        LoadDataGrid();
                    }
                    else
                    {
                        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "onclick", "MessageAlert('ไม่สามารถนำเข้าข้อมูลได้ เนื่องจากไฟล์นี้ได้มีการนำเข้าไปแล้ว')", true);
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Web.ShowAlert(this.Page, ex.Message);
            }
        }

        private int bindEmployeeTemp(ArrayList arrListEmp)
        {
            return 1;
        }

        protected void cmbEmpType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }

        protected void cmbWorkingJobSite_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadDataGrid();
        }
         
    }
}
